package com.personal.gateway.constant;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: FlinkGateway
 * @description: TODO 这里后续通过缓存的方式进行进行改造
 * @author: yangliao
 * @create: 2021-08-20
 */
@Slf4j
@Configuration
public class LoginUserInfoConstant {

    private static final long USER_EXPIRATION_TIME = 86400L;
    private static final long CAPTCHA_EXPIRATION_TIME = 60L;
    public static final String TOKEN = "token";
    public static final String LOGIN = "login";
    public static final String CAPTCHA = "captcha";
    private static final String CAPTCHA_PREFIX = CAPTCHA + "_";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 由于用户很少 用户登录信息存储起来 用户账户作为key token做value 一个用户只能在一个浏览器登录
     * <p>
     * <user, token>
     */
    public static final Map<String, String> user = new HashMap<>();

    /**
     * 用户缓存
     *
     * @param user  用户
     * @param token token
     */
    public void setUserToken(String user, String token) {
        redisTemplate.opsForValue().set(user, token, USER_EXPIRATION_TIME, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(token, user, USER_EXPIRATION_TIME, TimeUnit.SECONDS);
    }

    /**
     * 通过token获取用户
     *
     * @param token token
     * @return 用户String
     */
    public String getUserByToken(String token) {
        String user = redisTemplate.opsForValue().get(token);
        if (null == user) {
            return "";
        } else {
            return user;
        }
    }

    public boolean checkToken(String token) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(token));
    }


    /**
     * 验证码校验
     *
     * @param captchaId   验证码ID
     * @param captchaText 验证码值
     */
    public void setCaptcha(String captchaId, String captchaText) {
        redisTemplate.opsForValue().set(CAPTCHA_PREFIX + captchaId, captchaText, CAPTCHA_EXPIRATION_TIME, TimeUnit.SECONDS);
    }

    /**
     * 获取验证码值
     *
     * @param captchaId   验证码ID
     * @param captchaText 验证码值
     * @return 验证码校验结果
     */
    public boolean checkCaptcha(String captchaId, String captchaText) {
        if (Boolean.TRUE.equals(redisTemplate.hasKey(CAPTCHA_PREFIX + captchaId))) {
            String text = redisTemplate.opsForValue().get(CAPTCHA_PREFIX + captchaId);
            if (captchaText.equals(text)) {
                redisTemplate.delete(CAPTCHA_PREFIX + captchaId);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

}
